package sso.client2.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * see -http://blog.csdn.net/wangpeng047/article/details/19624529
 * see -http://blog.csdn.net/leeo1010/article/details/41801509
 */
@SuppressWarnings("all")
public class HttpClientUtil {

    private static Logger logger = LoggerFactory.getLogger(HttpClientUtil.class.getName());

    /**
     * 通过Get方法获取Json
     */
    public static JSONObject sendGet(String url) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(url);
        //如果不设置user-agent,用默认值User-Agent: Apache-HttpClient/4.5.2 (Java/1.8.0_144)可能会导致访问不成功。
        httpGet.setHeader("User-Agent","Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.86 Safari/537.36");
        //httpGet.setHeader("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36");
        CloseableHttpResponse response = null;
        JSONObject jsonObject = null;
        try {
            response = httpClient.execute(httpGet);
            //建立的http连接，仍旧被response保持着，允许我们从网络socket中获取返回的数据
            //为了释放资源，我们必须手动消耗掉response或者取消连接（使用CloseableHttpResponse类的close方法）
            HttpEntity entity = response.getEntity();
            // do something useful with the response body
            if(entity != null){
                String result = EntityUtils.toString(entity, "UTF-8");
                jsonObject = jsonObject.parseObject(result);
            }
            // and ensure it is fully consumed
            EntityUtils.consume(entity);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return jsonObject;
    }

    /**
     * 通过Post方法获取Json
     */
    public static JSONObject sendPost(String url, String postData) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        JSONObject jsonObject = null;
        //拼接参数
        JSONObject para = JSON.parseObject(postData);
        List<NameValuePair> list = new ArrayList<>();
        for(Map.Entry<String, Object> entry: para.entrySet()){
            list.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString()));
        }
        try {
            httpPost.setEntity(new UrlEncodedFormEntity(list));
            //httpPost.setHeader("","");
            HttpResponse response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            if(entity != null){
                String result = EntityUtils.toString(response.getEntity(), "UTF-8");
                jsonObject = jsonObject.parseObject(result);
            }
            //消耗掉response
            EntityUtils.consume(entity);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e){
            e.printStackTrace();
        }
        return jsonObject;
    }
}
